//
//  ChildMetrailVC.m
//  Cunli
//
//  Created by lilubin on 15/7/6.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "ChildMetrailVC.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "LearnModel.h"
#import "LearnCell.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "Config.h"
#import "MBProgressHUD.h"
#import "BookDetailVC.h"
#import "MediaDetailVC.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define pageSize 6

static NSString *kLearnCellID = @"LearnCell";

@interface ChildMetrailVC ()
{
    NSMutableArray *_datasArray; //存放学习中的数组
}

@end

@implementation ChildMetrailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.rowHeight = 90;
    [self reloadDataToNew:YES];
    [self registerNewsCell];
    [self addRefreshAttribute];
    self.tableView.separatorColor = [UIColor colorWithHexString:TableViewSeperateColorValue];
}

- (void)initGlobalParams
{
    _datasArray = [NSMutableArray arrayWithCapacity:6];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)addRefreshAttribute
{
    __weak typeof(self) weakSelf = self;
    
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:YES]; //刷新
    }];
    
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf reloadDataToNew:NO]; //加载更多
    }];
    
    //    [self.tableView.legendHeader beginRefreshing];
}

//注册tableViewCell
- (void)registerNewsCell
{
    UINib *nib = [UINib nibWithNibName:@"LearnCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kLearnCellID];
}

- (instancetype)initWithChildLearnType:(ChildLearnType)type
{
    self = [super init];
    if (self) {
        _matrailChildType = type;
        [self initGlobalParams];
    }
    return self;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _datasArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LearnCell *cell = [tableView dequeueReusableCellWithIdentifier:kLearnCellID forIndexPath:indexPath];
    cell.learnModel = _datasArray[indexPath.row];
    
//    UIImageView *videoMarkView = [[UIImageView alloc] initWithFrame:CGRectMake(33, 23, 44, 44)];
    CGFloat itemWidth = 40;
    UIImageView *videoMarkView = [[UIImageView alloc] initWithFrame:CGRectMake((cell.titleImgView.frame.size.width*1.0-itemWidth)/2.0+8, (cell.titleImgView.frame.size.height*1.0-itemWidth)/2.0+15, itemWidth, itemWidth)];

    [videoMarkView setImage:[UIImage imageNamed:@"video_icon"]];
    
    if (_matrailChildType == ChildLearnTypeVideo) {
        [cell.contentView addSubview:videoMarkView];
    }

    return cell;
}

//将cell的高度固定为120
/*
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
*/
//进入新闻的详情界面只需要传itemid的值即可

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LearnModel *model = _datasArray[indexPath.row];
    if (_matrailChildType == ChildLearnTypeBook) {
        BookDetailVC *detailVC = [[BookDetailVC alloc] init];
        detailVC.bookID = model.itemid;
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    else
    {
        MediaDetailVC *mediaVC = [[MediaDetailVC alloc] init];
        mediaVC.mediaID = model.itemid;
        mediaVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:mediaVC animated:YES];
    }
}

//加载数据
/*刷新or加载更多函数
 *@new
 *yes:刷新
 *no:加载更多
 */
- (void)reloadDataToNew:(BOOL)new
{
        NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
        
        NSString *typeStr = [NSString stringWithFormat:@"%d", _matrailChildType];
        
        NSUInteger page = 1;
        if (!new)  // new = NO 设置page
        {
            page = _datasArray.count/pageSize + 1; //根据当前数据数组中的数据量来判断应该加载第几页
        }
        
        NSString *pageStr = [NSString stringWithFormat:@"%lu", (unsigned long)page];
        
        [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
        [CheckParams setObject:typeStr forKey:@"type"];
        [CheckParams setObject:pageStr forKey:@"page"];
        [CheckParams setObject:@"6" forKey:@"pagesize"];
        
        NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
        [CheckParams setObject:resultSign forKey:@"sign"];
        [MyDataService requestURL:@"child_studylist.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
            NSString *response = [result objectForKey:@"response"];
            if ([response isEqualToString:@"child_studylist"]) {
                NSDictionary *newslistDic = result[@"studylist"];
                NSArray *newsList = newslistDic[@"list"];
                NSInteger totalCount = [newslistDic[@"totalcount"] integerValue];
                
                /*
                 *思路：判断是否是刷新
                 *是：移除dataArray中的数据，重新加载第一页
                 *否：加载下一页的数据，并且拼接到已存在的数据数组中
                 */
                if (new) {
                    if (_datasArray.count != 0) {
                        [_datasArray removeAllObjects]; //刷新时，将已有数据清除，加载最新数据
                    }
                }
                if (totalCount == _datasArray.count) {
                    MBProgressHUD *hud = [Config createHUD];
                    hud.mode = MBProgressHUDModeCustomView;
                    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
                    hud.labelText = @"没有更多数据";
                    [hud hide:YES afterDelay:1];
                    [self.tableView.footer setState:MJRefreshFooterStateNoMoreData];
                }
                else
                {
                    for(NSDictionary *dataDic in newsList)
                    {
//                        LearnModel *newModel = [[LearnModel alloc] initWithDataDic:dataDic];
                        LearnModel *newModel = [LearnModel yy_modelWithJSON:dataDic];
                        newModel.modelType = LearnModelTypeAuOrSpeaker;
                        [_datasArray addObject:newModel];
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [self.tableView.legendHeader endRefreshing];
                        [self.tableView.legendFooter endRefreshing];
                        [self.tableView reloadData];
                    });
                }
                
            }
            
            if ([response isEqualToString:@"error"]) {
                NSDictionary *errorDic = [result objectForKey:@"error"];
                NSString *text = errorDic[@"text"];
                MBProgressHUD *hud = [Config createHUD];
                hud.mode = MBProgressHUDModeCustomView;
                
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
                hud.labelText = text;
                [hud hide:YES afterDelay:1];
            }
            
        } failureAction:^{
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"数据错误";
            [hud hide:YES afterDelay:1];
            [self.tableView.legendHeader endRefreshing];
            [self.tableView.legendFooter endRefreshing];
            
        }];
}
@end
